package com.hongxun.design.fragments;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.CreateProjectActivity;
import com.hongxun.design.activitys.EncyclopediasActivity;
import com.hongxun.design.activitys.HomePageActivity;
import com.hongxun.design.adapters.HomeRootHeadGridAdapter;
import com.hongxun.design.bean.HomeCarouselBean;
import com.hongxun.design.bean.HomeListFunctionBean;
import com.hongxun.design.bean.ProjectItemBean;
import com.hongxun.design.bean.photopassbean.SystemTypeBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.listeners.MClickListener;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.ui.myslider.MyBaseSliderView;
import com.hongxun.design.ui.myslider.MyTextSliderView;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.FragmentUtil;
import com.hongxun.design.utils.TimeUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.GetFileUtil;
import com.hongxun.design.utils.httputil.HttpStringCodeTableUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.imageutil.UriUtil;
import com.hongxun.design.utils.projectdatautil.DataFactory;

import java.util.ArrayList;
import java.util.List;

public class HomeFragmentNew extends BaseFragment {

    private final String tag = "HomeFragment_Carousel";
    private View view;
    private HomePageActivity mHomeActivity;
    private SliderLayout sliderLayout;//轮播控件
    private GridView gridView;
    private LinearLayout lay1, lay2;

    private List<HomeCarouselBean> CarouselData = null;//轮播数据包
    private List<SystemTypeBean> projectType, designStage, projectSchedule;

    public TextView recent_project_bar;//最近项目bar
    public SimpleDraweeView project_image;//项目图片
    public TextView project_name;//项目名字
    public TextView project_type;//项目类型
    public TextView project_statel;//项目状态左
    public TextView project_stater;//项目状态右
    public TextView project_right;//右方箭头
    public TextView project_schedule;//项目进度
    public TextView project_datatype;//踩勘数据类型
    public RelativeLayout project_item, delect_icon;

    private TextView noproject_right;//右向箭头
    private RelativeLayout recent_project_item;//即刻体验

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null)
            view = inflater.inflate(R.layout.fragment_homenewlayout, container, false);
        initialization0();//控件
        setCarouselData();//轮播数据
        setGridViewData();//轮播数据
        setProjectData();//轮播数据
        return view;
    }

    //初始化
    private void initialization0() {
        projectType = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.projectType);//项目类型
        designStage = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.designStage);//设计阶段
        projectSchedule = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.projectSchedule);//项目类型

        mHomeActivity = (HomePageActivity) getActivity();
        sliderLayout = (SliderLayout) view.findViewById(R.id.view_slider);
        gridView = (GridView) view.findViewById(R.id.home_head_functions);
        lay1 = (LinearLayout) view.findViewById(R.id.home_lay1);
        lay2 = (LinearLayout) view.findViewById(R.id.home_lay2);

        project_item = (RelativeLayout) view.findViewById(R.id.project_item);
        recent_project_bar = (TextView) view.findViewById(R.id.recent_project_bar);
        project_image = (SimpleDraweeView) view.findViewById(R.id.project_image);
        project_name = (TextView) view.findViewById(R.id.project_name);
        project_type = (TextView) view.findViewById(R.id.project_type);
        project_statel = (TextView) view.findViewById(R.id.project_statel);
        project_stater = (TextView) view.findViewById(R.id.project_stater);
        project_right = (TextView) view.findViewById(R.id.project_right);
        project_schedule = (TextView) view.findViewById(R.id.project_schedule);
        project_datatype = (TextView) view.findViewById(R.id.project_datatype);
        delect_icon = (RelativeLayout) view.findViewById(R.id.delect_icon);

        noproject_right = (TextView) view.findViewById(R.id.noproject_right);
        recent_project_item = (RelativeLayout) view.findViewById(R.id.recent_project_item);
    }

    private void setGridViewData() {
        List<HomeListFunctionBean> FunctionData = DataUtil.getFunctions();
        HomeRootHeadGridAdapter rootHeadGridAdapter = new HomeRootHeadGridAdapter(FunctionData, mHomeActivity);
        gridView.setAdapter(rootHeadGridAdapter);//GridView适配
    }

    private void setProjectData() {
        final ProjectItemBean project = MyApp.currProject;
        if (MyApp.currProject != null && MyApp.currProject.getProject_id().length() != 0) {
            lay1.setVisibility(View.GONE);
            lay2.setVisibility(View.VISIBLE);
        } else {
            lay2.setVisibility(View.GONE);
            lay1.setVisibility(View.VISIBLE);
            SetTypeface.set(noproject_right, IconSourse.RIGHTTOARROW);
            recent_project_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (MyApp.userInfo.getOrg_type().equalsIgnoreCase("11")) {
                        ToastShow.showShort(mHomeActivity, "业主单位人员不能创建项目!");
                        return;
                    }
                    IntentToActivity.intent(mHomeActivity, CreateProjectActivity.class);
                }
            });
        }
        recent_project_bar.setVisibility(View.VISIBLE);
        project_image.setImageURI(UriUtil.getUri(project.getThumb()));
        project_name.setText(project.getProject_name());
        if (project.getIs_exp().equals(MString.code_zero)) {
            project_datatype.setVisibility(View.GONE);
        } else {
            project_datatype.setVisibility(View.VISIBLE);
        }
        project_type.setText(getProjectType(project.getProject_type()));
        project_statel.setText(getDesignStage(project.getStage()));
        project_stater.setText(getProjectSchedule(project.getCurrent_schedule()));
        SetTypeface.set(project_right, IconSourse.RIGHTARROW);
        project_schedule.setText(TimeUtil.time(project.create_time + "000"));
        project_item.setOnClickListener(new MClickListener(0, project) {
            @Override
            public void onClick(View view, int position, Object msg) {
                ProjectItemBean itemBean = new ProjectItemBean();
                itemBean.setBean(project, 1);
                DataFactory.ProjectItemClick(mHomeActivity, itemBean);//点击判断函数
            }
        });
        if (project.getFlag().equals(MString.del)) {
            delect_icon.setVisibility(View.VISIBLE);
        } else {
            delect_icon.setVisibility(View.GONE);
        }
    }

    //初始化数据
    private void initializationData() {
        addCarouselItem(CarouselData);
    }

    @Override
    public void Refresh() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (MyApp.currProject != null && MString.getValueId(MyApp.currProject.getProject_id(),
                        MyApp.currProject.getUUID()).length() != 0) {
                    if (MyApp.currProject.getCost_center().equalsIgnoreCase(MyApp.userInfo.getOrg_id())) {
                        if (checkProject()) {
                            setProjectData();
                        }
                    }
                }
            }
        });
        super.Refresh();
    }


    private boolean checkProject() {
        if (MyApp.currProject == null) return false;
        List<ProjectItemBean> data = GetFileUtil.getProjectStageListFile();
        if (data == null || data.size() == 0) {
            MyApp.currProject.saveNullBean();
            return false;
        } else {
            for (ProjectItemBean bean : data) {
                if (checkId(bean.getStage_id()) && bean.getStage_id().equals(MyApp.currProject.getStage_id())) {
                    MyApp.currProject.setBean(bean);
                    return true;
                } else if (!checkId(bean.getStage_id()) && bean.getUUID().equals(MyApp.currProject.getUUID()) && checkId(bean.getUUID())) {
                    MyApp.currProject.setBean(bean);
                    return true;
                } else if (checkId(bean.getStage_id()) && checkId(bean.getUUID()) && bean.getUUID().equals(MyApp.currProject.getUUID())) {
                    MyApp.currProject.setBean(bean);
                    return true;
                }
            }
            MyApp.currProject.saveNullBean();
            return false;
        }
    }

    private boolean checkId(String id) {
        return id != null && id.length() > 0 && !id.equals(MString.code_zero);
    }

    List<MyTextSliderView> views = new ArrayList<>();

    private void addCarouselItem(List<HomeCarouselBean> list) {
        int i = 0;
        if (list.size() < views.size()) {
            List<Integer> l = new ArrayList<>();
            for (int j = list.size(); j < views.size(); j++) {
                l.add(j);
            }
            if (l.size() > 0) {
                for (int ll : l) {
                    views.remove(ll);
                    sliderLayout.removeSliderAt(ll);
                }
            }
        }
        boolean flag = true;
        for (HomeCarouselBean home : list) {
            if (i < views.size()) {
                flag = false;
                getMyTextSliderView(home, views.get(i)).update();
            } else {
                MyTextSliderView textSliderView = getMyTextSliderView(home, null);
                views.add(textSliderView);
                sliderLayout.addSlider(textSliderView);
            }
            i++;
        }

        for (HomeCarouselBean home : list) {
            sliderLayout.moveNextPosition();
        }
        if (list.size() > 0) {
            sliderLayout.setPresetTransformer(SliderLayout.Transformer.Default);//动画
            sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
            if (list.size() == 1) {
                sliderLayout.setIndicatorVisibility(PagerIndicator.IndicatorVisibility.Invisible);
            } else {
                sliderLayout.setIndicatorVisibility(PagerIndicator.IndicatorVisibility.Visible);
            }
            sliderLayout.stopAutoCycle();
            if (flag) {
                sliderLayout.setCurrentPosition(0);
            }
            sliderLayout.setVisibility(View.VISIBLE);
        } else {
            sliderLayout.setVisibility(View.GONE);
        }
    }

    private MyTextSliderView getMyTextSliderView(HomeCarouselBean home, MyTextSliderView textSliderView) {
        if (textSliderView == null) textSliderView = new MyTextSliderView(getActivity());
        String title = home.getTitle();
        String imageUrl = home.getImageUrl();
        String outUrl = home.getOutUrl();
        textSliderView.description(title).setHasTitle(false)
                .image(imageUrl)
                .outUrl(outUrl)
                .error(R.mipmap.accountbitmap)
                .setScaleType(MyBaseSliderView.ScaleType.Fit)
                .setOnSliderClickListener(new MyBaseSliderView.OnSliderClickListener() {
                    @Override
                    public void onSliderClick(MyBaseSliderView slider) {
                        Bundle bundle = new Bundle();
                        bundle.putString(MString.TYPE, MString.Carouse);
                        bundle.putString(MString.CODE, slider.getOutUrl());
                        bundle.putString(MString.TITLE, slider.getDescription());
                        IntentToActivity.intent(getActivity(), EncyclopediasActivity.class, bundle);
                    }
                });
        return textSliderView;
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    private void setCarouselData() {
        if (CarouselData == null) {
            CarouselData = new ArrayList<>();
        } else {
            CarouselData.clear();
        }
        addCarouselHandler();
        String s = MyApp.File.getJson(tag);
        if (s != null && s.length() > 0) {
            carouselHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, s));
        }
        MyApp.HTTP.getCarousel(carouselHandler, HttpStringUtil.SUCCESSED);
    }

    /**
     * 首页图片轮播*
     */
    private Handler carouselHandler;

    private void addCarouselHandler() {
        carouselHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            CarouselData.clear();
                            CarouselData.addAll(FastJsonUtil.JsonToDataCarousel((String) msg.obj));
                            MyApp.File.SaveFileData(tag, (String) msg.obj);
                            carouselHandler.sendEmptyMessage(1);
                        } else {
                            String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                            ToastShow.showShort(getActivity(), s);
                        }
                        break;
                    case 1:
                        initializationData();
                        break;
                    case HttpStringUtil.ERROR:
                        carouselHandler.sendEmptyMessage(1);
                        break;
                }
            }
        };
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        FragmentUtil.currFragTag = Constant.FRAGMENT_FLAG_HOME;
        if (MyApp.isupdate) {
            Refresh();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        CarouselData = null;
        sliderLayout.stopAutoCycle();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }


    private String getProjectType(String code) {
        if (projectType == null)
            projectType = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.projectType);//项目类型
        for (SystemTypeBean s : projectType) {
            if (s.getTypecode().equals(code)) {
                return s.getTypename();
            }
        }
        return "";
    }

    private String getDesignStage(String code) {
        if (designStage == null)
            designStage = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.designStage);//设计阶段
        for (SystemTypeBean s : designStage) {
            if (s.getTypecode().equals(code)) {
                return s.getTypename();
            }
        }
        return "";
    }

    private String getProjectSchedule(String code) {
        if (projectSchedule == null)
            projectSchedule = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.projectSchedule);//项目类型
        for (SystemTypeBean s : projectSchedule) {
            if (s.getTypecode().equals(code)) {
                return s.getTypename();
            }
        }
        return "";
    }

}
